package com.yuyu.shop.api.controller.order;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuyu.commons.annotation.NoAuth;
import com.yuyu.commons.interceptor.response.ResponseJson;
import com.yuyu.shop.api.apimodel.order.dto.OrderCreateDTO;
import com.yuyu.shop.api.apimodel.order.dto.OrderSaveOrUpdateDTO;
import com.yuyu.shop.api.apimodel.order.dto.QueryOrderByUserIdDTO;
import com.yuyu.shop.api.apimodel.order.vo.OrderInfoVO;
import com.yuyu.shop.api.controller.blockhandler.OrderApiBlockHandler;
import com.yuyu.shop.api.convert.OrderConvert;
import com.yuyu.shop.application.service.tcc.OrderAssembleTccService;
import com.yuyu.shop.domain.order.DO.OrderCreateDO;
import com.yuyu.shop.domain.order.DO.OrderDO;
import com.yuyu.shop.domain.order.service.OrderDomainService;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Objects;

/**
 * @author 订单信息相关接口
 * @version 1.0
 * @description: TODO
 * @date 2022/8/3 14:37
 */
@AllArgsConstructor(onConstructor = @_(@Autowired))
@RestController
@RequestMapping("/order")
public class OrderController {

    private final OrderDomainService orderDomainService;

    private final OrderAssembleTccService orderAssembleTccService;

    @GetMapping("/queryByOrderId")
    @ApiOperation("通过orderId查询订单")
    @SentinelResource(value = "queryOrderByOrderId",blockHandler ="queryOrderBlock" ,blockHandlerClass = OrderApiBlockHandler.class)
    public ResponseJson<OrderInfoVO> queryOrderByOrderId(@NotNull(message = "订单Id不能为空") @RequestParam String orderId){
        OrderInfoVO orderInfoVO = OrderConvert.orderDO2OrderInfoVO(OrderDO.getByOrderId(orderId));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ResponseJson.success(orderInfoVO);
    }


    @ApiOperation("保存或修改一个订单")
    @PostMapping("/saveOrUpdate")
    public Boolean saveOrder(@Valid @RequestBody OrderSaveOrUpdateDTO dto){
        OrderDO orderDO = OrderConvert.saveOrUpdateDTO2DO(dto);
        return Objects.requireNonNull(orderDO).saveOrUpdate();
    }

    @ApiOperation("创建预订单信息")
    @GlobalTransactional
    @PostMapping("/create")
    public OrderCreateDO createOrder(@Valid @RequestBody OrderCreateDTO dto){
        return new OrderDO().createOrder(null,dto);
    }

    @ApiOperation("查询用户订单")
    @PostMapping("/queryOrderByUserId")
    public Page<OrderInfoVO> queryOrderByUserId(@Valid @RequestBody QueryOrderByUserIdDTO dto){
      return  orderDomainService.queryOrderByUserId(dto);
    }


}
